def count_char(file_path, target):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
        count = content.count(target)
    return count

def delete_string(file_path, target):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    content = content.replace(target, '')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)

def find_and_replace(file_path, target, replacement):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    content = content.replace(target, replacement)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)

file_path = 'python_learn.txt'

# 统计字符出现次数
target = '学习'
count = count_char(file_path, target)
print(f"{target} 在 {file_path} 中出现的次数为：{count}")

# 统计字符出现次数
target = 'love'
count = count_char(file_path, target)
print(f"{target} 在 {file_path} 中出现的次数为：{count}")

# # 删除字符串
# delete_string(file_path, target)
# print(f"已从 {file_path} 中删除 {target}")

# 查找并替换
target = '学习'
replacement = 'love'
find_and_replace(file_path, target, replacement)
print(f"已将 {file_path} 中的 {target} 替换为 {replacement}")

# 统计字符出现次数
target = '学习'
count = count_char(file_path, target)
print(f"{target} 在 {file_path} 中出现的次数为：{count}")

# 统计字符出现次数
target = 'love'
count = count_char(file_path, target)
print(f"{target} 在 {file_path} 中出现的次数为：{count}")
